<template>
  <div class="settings">
    <div class="page-header">
      <h1>设置</h1>
      <p class="subtitle">管理您的账户和系统设置</p>
    </div>

    <div class="settings-content">
      <el-tabs v-model="activeTab" class="settings-tabs">
        <!-- Profile Settings -->
        <el-tab-pane label="个人资料" name="profile">
          <el-card class="settings-card">
            <template #header>
              <h3>个人资料</h3>
            </template>
            
            <el-form
              ref="profileFormRef"
              :model="profileForm"
              :rules="profileRules"
              label-width="100px"
            >
              <el-form-item label="头像">
                <div class="avatar-section">
                  <el-avatar :size="80" :src="profileForm.avatar">
                    {{ profileForm.username?.charAt(0).toUpperCase() }}
                  </el-avatar>
                  <div class="avatar-actions">
                    <el-button size="small" @click="handleAvatarUpload">
                      更换头像
                    </el-button>
                    <p class="avatar-tip">支持 JPG、PNG 格式，文件大小不超过 2MB</p>
                  </div>
                </div>
              </el-form-item>
              
              <el-form-item label="用户名" prop="username">
                <el-input v-model="profileForm.username" disabled />
              </el-form-item>
              
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="profileForm.email" />
              </el-form-item>
              
              <el-form-item label="显示名称" prop="displayName">
                <el-input v-model="profileForm.displayName" placeholder="请输入显示名称" />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" :loading="profileLoading" @click="handleUpdateProfile">
                  保存更改
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>

        <!-- Security Settings -->
        <el-tab-pane label="安全设置" name="security">
          <el-card class="settings-card">
            <template #header>
              <h3>修改密码</h3>
            </template>
            
            <el-form
              ref="passwordFormRef"
              :model="passwordForm"
              :rules="passwordRules"
              label-width="100px"
            >
              <el-form-item label="当前密码" prop="currentPassword">
                <el-input
                  v-model="passwordForm.currentPassword"
                  type="password"
                  show-password
                  placeholder="请输入当前密码"
                />
              </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input
                  v-model="passwordForm.newPassword"
                  type="password"
                  show-password
                  placeholder="请输入新密码"
                />
              </el-form-item>
              
              <el-form-item label="确认密码" prop="confirmPassword">
                <el-input
                  v-model="passwordForm.confirmPassword"
                  type="password"
                  show-password
                  placeholder="请再次输入新密码"
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" :loading="passwordLoading" @click="handleChangePassword">
                  修改密码
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>

        <!-- API Keys -->
        <el-tab-pane label="API 密钥" name="apiKeys">
          <el-card class="settings-card">
            <template #header>
              <div class="card-header">
                <h3>API 密钥管理</h3>
                <el-button type="primary" @click="showCreateKeyDialog = true">
                  <el-icon><Plus /></el-icon>
                  创建密钥
                </el-button>
              </div>
            </template>
            
            <div v-loading="keysLoading" class="api-keys-list">
              <div v-if="apiKeys.length === 0" class="empty-state">
                <el-icon><Key /></el-icon>
                <p>暂无 API 密钥</p>
                <el-button type="primary" @click="showCreateKeyDialog = true">
                  创建第一个密钥
                </el-button>
              </div>
              
              <div v-else>
                <div v-for="key in apiKeys" :key="key.id" class="api-key-item">
                  <div class="key-info">
                    <h4>{{ key.name }}</h4>
                    <p class="key-description">{{ key.description || '暂无描述' }}</p>
                    <div class="key-meta">
                      <span class="key-created">创建于 {{ formatDate(key.createdAt) }}</span>
                      <span class="key-expires">过期时间 {{ key.expiresAt ? formatDate(key.expiresAt) : '永不过期' }}</span>
                    </div>
                  </div>
                  <div class="key-actions">
                    <el-button size="small" @click="handleCopyKey(key)">
                      复制
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDeleteKey(key)">
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-tab-pane>

        <!-- Preferences -->
        <el-tab-pane label="偏好设置" name="preferences">
          <el-card class="settings-card">
            <template #header>
              <h3>偏好设置</h3>
            </template>
            
            <el-form label-width="120px">
              <el-form-item label="语言">
                <el-select v-model="preferences.language" @change="handleLanguageChange">
                  <el-option label="简体中文" value="zh-CN" />
                  <el-option label="English" value="en-US" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="主题">
                <el-radio-group v-model="preferences.theme" @change="handleThemeChange">
                  <el-radio label="light">浅色</el-radio>
                  <el-radio label="dark">深色</el-radio>
                  <el-radio label="auto">跟随系统</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="邮件通知">
                <el-switch
                  v-model="preferences.emailNotifications"
                  @change="handleNotificationChange"
                />
              </el-form-item>
              
              <el-form-item label="桌面通知">
                <el-switch
                  v-model="preferences.desktopNotifications"
                  @change="handleNotificationChange"
                />
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- Create API Key Dialog -->
    <el-dialog
      v-model="showCreateKeyDialog"
      title="创建 API 密钥"
      width="500px"
      @close="resetKeyForm"
    >
      <el-form
        ref="keyFormRef"
        :model="keyForm"
        :rules="keyRules"
        label-width="80px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="keyForm.name" placeholder="请输入密钥名称" />
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input
            v-model="keyForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入密钥描述（可选）"
          />
        </el-form-item>
        
        <el-form-item label="过期时间">
          <el-date-picker
            v-model="keyForm.expiresAt"
            type="datetime"
            placeholder="选择过期时间（可选）"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateKeyDialog = false">取消</el-button>
        <el-button type="primary" :loading="createKeyLoading" @click="handleCreateKey">
          创建
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Plus, Key } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

const activeTab = ref('profile')
const profileLoading = ref(false)
const passwordLoading = ref(false)
const keysLoading = ref(false)
const createKeyLoading = ref(false)
const showCreateKeyDialog = ref(false)

const profileFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const keyFormRef = ref<FormInstance>()

const profileForm = reactive({
  username: '',
  email: '',
  displayName: '',
  avatar: ''
})

const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const keyForm = reactive({
  name: '',
  description: '',
  expiresAt: ''
})

const preferences = reactive({
  language: 'zh-CN',
  theme: 'light',
  emailNotifications: true,
  desktopNotifications: false
})

const apiKeys = ref<any[]>([])

const profileRules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const passwordRules: FormRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const keyRules: FormRules = {
  name: [
    { required: true, message: '请输入密钥名称', trigger: 'blur' },
    { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

const loadProfile = async () => {
  try {
    // TODO: Load user profile from API
    // const response = await getUserProfile()
    // Object.assign(profileForm, response.data)
    
    // Mock data for now
    if (authStore.user) {
      profileForm.username = authStore.user.username
      profileForm.email = authStore.user.email
      profileForm.displayName = authStore.user.displayName || ''
      profileForm.avatar = authStore.user.avatar || ''
    }
  } catch (error) {
    ElMessage.error('加载个人资料失败')
  }
}

const loadApiKeys = async () => {
  keysLoading.value = true
  try {
    // TODO: Load API keys from API
    // const response = await getApiKeys()
    // apiKeys.value = response.data
    
    // Mock data for now
    apiKeys.value = []
  } catch (error) {
    ElMessage.error('加载 API 密钥失败')
  } finally {
    keysLoading.value = false
  }
}

const handleAvatarUpload = () => {
  ElMessage.info('头像上传功能开发中')
}

const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    await profileFormRef.value.validate()
    profileLoading.value = true
    
    // TODO: Update user profile via API
    // await updateUserProfile(profileForm)
    
    ElMessage.success('个人资料更新成功')
  } catch (error: any) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('更新个人资料失败，请重试')
    }
  } finally {
    profileLoading.value = false
  }
}

const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    passwordLoading.value = true
    
    // TODO: Change password via API
    // await changePassword(passwordForm)
    
    ElMessage.success('密码修改成功')
    passwordForm.currentPassword = ''
    passwordForm.newPassword = ''
    passwordForm.confirmPassword = ''
  } catch (error: any) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('修改密码失败，请重试')
    }
  } finally {
    passwordLoading.value = false
  }
}

const handleCreateKey = async () => {
  if (!keyFormRef.value) return
  
  try {
    await keyFormRef.value.validate()
    createKeyLoading.value = true
    
    // TODO: Create API key via API
    // await createApiKey(keyForm)
    
    ElMessage.success('API 密钥创建成功')
    showCreateKeyDialog.value = false
    resetKeyForm()
    loadApiKeys()
  } catch (error: any) {
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('创建 API 密钥失败，请重试')
    }
  } finally {
    createKeyLoading.value = false
  }
}

const handleCopyKey = (key: any) => {
  // TODO: Copy API key to clipboard
  ElMessage.info('复制功能开发中')
}

const handleDeleteKey = async (key: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 API 密钥 "${key.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: Delete API key via API
    // await deleteApiKey(key.id)
    
    ElMessage.success('API 密钥删除成功')
    loadApiKeys()
  } catch (error) {
    // User cancelled or error occurred
  }
}

const handleLanguageChange = (language: string) => {
  ElMessage.success(`语言已切换为 ${language === 'zh-CN' ? '简体中文' : 'English'}`)
}

const handleThemeChange = (theme: string) => {
  ElMessage.success(`主题已切换为 ${theme === 'light' ? '浅色' : theme === 'dark' ? '深色' : '跟随系统'}`)
}

const handleNotificationChange = () => {
  ElMessage.success('通知设置已更新')
}

const resetKeyForm = () => {
  keyForm.name = ''
  keyForm.description = ''
  keyForm.expiresAt = ''
  keyFormRef.value?.resetFields()
}

onMounted(() => {
  loadProfile()
  loadApiKeys()
})
</script>

<style scoped>
.settings {
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.settings-content {
  background: white;
  border-radius: 8px;
}

.settings-tabs {
  padding: 0;
}

.settings-card {
  border: none;
  box-shadow: none;
}

.settings-card .el-card__header {
  padding: 0 0 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.settings-card .el-card__body {
  padding: 20px 0 0 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-actions {
  flex: 1;
}

.avatar-tip {
  margin: 8px 0 0 0;
  font-size: 12px;
  color: #909399;
}

.api-keys-list {
  min-height: 200px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #c0c4cc;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.api-key-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.api-key-item:last-child {
  border-bottom: none;
}

.key-info {
  flex: 1;
}

.key-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.key-description {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #909399;
}

.key-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #c0c4cc;
}

.key-actions {
  display: flex;
  gap: 8px;
}

@media (max-width: 768px) {
  .avatar-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .api-key-item {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .key-actions {
    justify-content: flex-end;
  }
}
</style>